// 文件路径: F:\编程开发\创域家\zcn_admin\txz-mall\src\main\java\com\txz\system\controller\ZcnDiyTemplateController.java
package com.txz.system.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.txz.common.annotation.Log;
import com.txz.common.annotation.Anonymous;
import com.txz.common.core.controller.BaseController;
import com.txz.common.core.domain.AjaxResult;
import com.txz.common.enums.BusinessType;
import com.txz.system.domain.ZcnDiyTemplate;
import com.txz.system.service.IZcnDiyTemplateService;
import com.txz.common.utils.poi.ExcelUtil;
import com.txz.common.core.page.TableDataInfo;

/**
 * DIY模板Controller
 *
 * @author tuxiaozhuo
 * @date 2025-10-25
 */
@RestController
@RequestMapping("/api/app/diy-template")
public class ZcnDiyTemplateController extends BaseController
{
    @Autowired
    private IZcnDiyTemplateService zcnDiyTemplateService;

    /**
     * 获取正在使用的DIY模板
     */
    @Anonymous
    @GetMapping("/used")
    public AjaxResult getUsedDiyTemplate()
    {
        ZcnDiyTemplate template = zcnDiyTemplateService.selectUsedDiyTemplate();
        if (template == null) {
            // 如果没有正在使用的模板，返回默认模板数据
            template = createDefaultTemplate();
        }

        // 构建返回数据，确保格式与前端期望一致
        Map<String, Object> result = new HashMap<>();

        // 处理首页数据
        if (template.getHome() != null) {
            try {
                // 解析JSON字符串为对象
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> homeData = objectMapper.readValue(template.getHome(), Map.class);
                result.put("home", homeData);
            } catch (Exception e) {
                e.printStackTrace();
                // 如果解析失败，返回空对象
                result.put("home", new HashMap<>());
            }
        } else {
            result.put("home", new HashMap<>());
        }

        // 处理用户中心数据
        if (template.getUser() != null) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> userData = objectMapper.readValue(template.getUser(), Map.class);
                result.put("user", userData);
            } catch (Exception e) {
                e.printStackTrace();
                result.put("user", new HashMap<>());
            }
        } else {
            result.put("user", new HashMap<>());
        }

        // 处理底部导航数据
        if (template.getTabBar() != null) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> tabBarData = objectMapper.readValue(template.getTabBar(), Map.class);
                result.put("property", new HashMap<>());
                ((Map)result.get("property")).put("tabBar", tabBarData);
            } catch (Exception e) {
                e.printStackTrace();
                result.put("property", new HashMap<>());
            }
        } else {
            result.put("property", new HashMap<>());
        }

        return success(result);
    }

    /**
     * 获取指定ID的DIY模板
     */
    @Anonymous
    @GetMapping("/get")
    public AjaxResult getDiyTemplate(Long id)
    {
        ZcnDiyTemplate template = zcnDiyTemplateService.selectZcnDiyTemplateById(id);
        if (template == null) {
            return error("模板不存在");
        }
        return success(template);
    }

    /**
     * 获取DIY模板列表
     */
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(ZcnDiyTemplate zcnDiyTemplate)
    {
        startPage();
        List<ZcnDiyTemplate> list = zcnDiyTemplateService.selectZcnDiyTemplateList(zcnDiyTemplate);
        return getDataTable(list);
    }

    /**
     * 新增DIY模板
     */
    @PreAuthorize("@ss.hasPermi('system:diyTemplate:add')")
    @Log(title = "DIY模板", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZcnDiyTemplate zcnDiyTemplate)
    {
        return toAjax(zcnDiyTemplateService.insertZcnDiyTemplate(zcnDiyTemplate));
    }

    /**
     * 修改DIY模板
     */
    @PreAuthorize("@ss.hasPermi('system:diyTemplate:edit')")
    @Log(title = "DIY模板", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZcnDiyTemplate zcnDiyTemplate)
    {
        return toAjax(zcnDiyTemplateService.updateZcnDiyTemplate(zcnDiyTemplate));
    }

    /**
     * 删除DIY模板
     */
    @PreAuthorize("@ss.hasPermi('system:diyTemplate:remove')")
    @Log(title = "DIY模板", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(zcnDiyTemplateService.deleteZcnDiyTemplateByIds(ids));
    }

    /**
     * 设置使用的DIY模板
     */
    @PreAuthorize("@ss.hasPermi('system:diyTemplate:edit')")
    @Log(title = "DIY模板", businessType = BusinessType.UPDATE)
    @PutMapping("/set-used/{id}")
    public AjaxResult setUsed(@PathVariable Long id)
    {
        // 先将所有模板设置为未使用
        ZcnDiyTemplate updateTemplate = new ZcnDiyTemplate();
        updateTemplate.setIsUsed(0L);
        zcnDiyTemplateService.updateAllTemplateUsedStatus(updateTemplate);
        
        // 设置指定模板为已使用
        ZcnDiyTemplate template = zcnDiyTemplateService.selectZcnDiyTemplateById(id);
        if (template == null) {
            return error("模板不存在");
        }
        template.setIsUsed(1L);
        return toAjax(zcnDiyTemplateService.updateZcnDiyTemplate(template));
    }

    /**
     * 创建默认模板数据
     */
    private ZcnDiyTemplate createDefaultTemplate() {
        ZcnDiyTemplate template = new ZcnDiyTemplate();
        template.setId(1L);
        template.setName("默认模板");
        template.setIsUsed(1L);
        template.setType(0L);

        // 设置默认首页配置
        String defaultHome = "{\n" +
                "  \"components\": [\n" +
                "    {\n" +
                "      \"id\": \"search-bar\",\n" +
                "      \"property\": {\n" +
                "        \"style\": {\n" +
                "          \"paddingTop\": \"10px\",\n" +
                "          \"paddingLeft\": \"10px\",\n" +
                "          \"paddingRight\": \"10px\",\n" +
                "          \"paddingBottom\": \"10px\"\n" +
                "        }\n" +
                "      }\n" +
                "    },\n" +
                "    {\n" +
                "      \"id\": \"swiper\",\n" +
                "      \"property\": {\n" +
                "        \"style\": {\n" +
                "          \"paddingTop\": \"10px\",\n" +
                "          \"paddingLeft\": \"10px\",\n" +
                "          \"paddingRight\": \"10px\",\n" +
                "          \"paddingBottom\": \"10px\"\n" +
                "        },\n" +
                "        \"data\": {\n" +
                "          \"list\": [\n" +
                "            {\n" +
                "              \"src\": \"https://pic.nximg.cn/file/20230629/12419049_155455999128_2.jpg\",\n" +
                "              \"url\": \"/pages/goods/index\"\n" +
                "            }\n" +
                "          ]\n" +
                "        }\n" +
                "      }\n" +
                "    },\n" +
                "    {\n" +
                "      \"id\": \"goods-card\",\n" +
                "      \"property\": {\n" +
                "        \"style\": {\n" +
                "          \"paddingTop\": \"10px\",\n" +
                "          \"paddingLeft\": \"10px\",\n" +
                "          \"paddingRight\": \"10px\",\n" +
                "          \"paddingBottom\": \"10px\"\n" +
                "        },\n" +
                "        \"data\": {\n" +
                "          \"list\": []\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        template.setHome(defaultHome);

        // 设置默认用户中心配置
        String defaultUser = "{\n" +
                "  \"components\": [\n" +
                "    {\n" +
                "      \"id\": \"user-card\",\n" +
                "      \"property\": {\n" +
                "        \"style\": {\n" +
                "          \"paddingTop\": \"10px\",\n" +
                "          \"paddingLeft\": \"10px\",\n" +
                "          \"paddingRight\": \"10px\",\n" +
                "          \"paddingBottom\": \"10px\"\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        template.setUser(defaultUser);

        // 设置默认底部导航配置
        String defaultTabBar = "{\n" +
                "  \"items\": [\n" +
                "    {\n" +
                "      \"text\": \"首页\",\n" +
                "      \"iconPath\": \"/static/tabbar/home.png\",\n" +
                "      \"selectedIconPath\": \"/static/tabbar/home-active.png\",\n" +
                "      \"url\": \"/pages/index/index\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"text\": \"分类\",\n" +
                "      \"iconPath\": \"/static/tabbar/category.png\",\n" +
                "      \"selectedIconPath\": \"/static/tabbar/category-active.png\",\n" +
                "      \"url\": \"/pages/index/category\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"text\": \"购物车\",\n" +
                "      \"iconPath\": \"/static/tabbar/cart.png\",\n" +
                "      \"selectedIconPath\": \"/static/tabbar/cart-active.png\",\n" +
                "      \"url\": \"/pages/index/cart\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"text\": \"我的\",\n" +
                "      \"iconPath\": \"/static/tabbar/user.png\",\n" +
                "      \"selectedIconPath\": \"/static/tabbar/user-active.png\",\n" +
                "      \"url\": \"/pages/index/user\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        template.setTabBar(defaultTabBar);

        return template;
    }
}
